package com.example.server;

import com.example.util.iotDao;
import javafx.scene.control.TextArea;
import java.io.BufferedReader;
import java.io.*;

import java.net.Socket;
import java.util.Scanner;

public class Handler implements Runnable{

    Socket socket;
    TextArea message;

    public Handler(){ super(); }

    public Handler(TextArea message,Socket socket){
        super();
        this.message = message;
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            InputStream in = socket.getInputStream();//捕捉异常
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
            //OutputStream out = socket.getOutputStream();
            //PrintWriter pWriter = new PrintWriter(out);
            //pWriter数据打印、发送数据等其它事项

            //收消息
            String msg;
            message.appendText("数据：" + "\n");//成功输出
            int i = 1;
            String address = "";
            String date = "";
            String time = "";
            String temperature = "";
            String humidity = "";
            String co2 = "";
            String lux = "";

            iotDao iD = new iotDao();
//            iD.createTable(address);

            while (true) {
                if(ServerController.thread.isInterrupted())
                    break;

                //将接收TextArea中的信息拆分存入数据库
                msg = bufferedReader.readLine();
                Scanner scanner=new Scanner(msg);
                if(scanner.hasNext()){   //循环六次
                    if(i == 8) {
                        i = 1;
                        //将产生的随机数据传到数据库表单中
                        iD.addData(address, date,time,temperature,humidity,co2,lux);
                    }
                    switch(i){
                        case 1:
                            address = scanner.nextLine();
                            break;
                        case 2:
                            date = scanner.nextLine();
                            break;
                        case 3:
                            time = scanner.nextLine();
                            break;
                        case 4:
                            temperature = scanner.nextLine();
                            break;
                        case 5:
                            humidity = scanner.nextLine();
                            break;
                        case 6:
                            co2 = scanner.nextLine();
                            break;
                        case 7:
                            lux = scanner.nextLine();
                            break;
                    }
                    i++;
                }
                message.appendText(msg + "\n");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
